<?php


namespace App\Services\Game;

use App\DTOS\Admin\GamePackageDTO;
use App\DTOS\Admin\GameVersionDTO;
use App\Models\Game\ChannelPackage;
use App\Models\Game\ConfigGroup;
use App\Models\Game\GameChannel;
use App\Models\Game\GamePackage;
use App\Models\Game\GameVersion;
use App\Utils\MyLog;
use Illuminate\Support\Facades\DB;

class GameVersionService
{
    public function paginate(GameVersionDTO $DTO){
        $model = GameVersion::query();
        $pageSize = $DTO->getLimit();
        $page = $DTO->getPage();
        $name = $DTO->getName();
        $mark = $DTO->getMark();
        if ($name){
            $model->where('name',$name);
        }
        if($mark){
            $model->where('mark',$mark);
        }

        return $model->orderByDesc('id')->paginate($pageSize,'*','page',$page);
    }

    /**
     * @param $data ['package_no','version_name','game_channel_id','description']
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function add($data){

        DB::beginTransaction();
        try {
            $insertData = array_only($data,['name','description','mark','channel','api_url']);
            $data['created_at'] = date("Y-m-d H:i:s");
          GameVersion::query()->insertGetId($insertData);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function edit($Id,$data){
        DB::beginTransaction();
        try {
            $updateData =  array_only($data,['name','description','mark','channel','api_url']);
            MyLog::info('修改的参数'.json_encode($updateData));
            $data['updated_at'] = date("Y-m-d H:i:s");
            GameVersion::query()->where('id',$Id)->update($updateData);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function delete($Id){
        DB::beginTransaction();
        try {
            GameVersion::query()->where('id',$Id)->delete();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    /**
     * @param $Id
     * @return array
     */
    public function detail($Id)
    {
        $gamePackage = GameVersion::query()->find($Id);
        $gamePackageArray = $gamePackage->toArray();

        return $gamePackageArray;
    }
}
